package com.good.child.ui.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.good.child.R;
import com.good.child.config.OFApplication;
import com.good.child.http.CommonLogical;
import com.yimidida.library.utils.LogUtils;

/**
 * Create on: 2024/8/21
 * by Mr.Zhu
 * Description: 位置更新服务
 */
public class LocationUpdateService extends Service {
    public static final String ACTION_STOP = "com.good.child.LocationUpdateService.stop";
    private DaemonReceiver daemonReceiver;
    private PowerManager.WakeLock wakeLock = null;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    @Override
    public void onCreate() {
        super.onCreate();
        try {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel("task", "task", NotificationManager.IMPORTANCE_HIGH);
                manager.createNotificationChannel(channel);
                builder.setChannelId(channel.getId());
            }
            Notification notification = builder.setSmallIcon(getApplicationInfo().icon)
                    .setContentTitle(getString(R.string.str_background_upload_server))
                    .build();
            startForeground(1, notification);
        } catch (Throwable e) {
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_STOP);
        registerReceiver(this);
    }

    public void registerReceiver(Context context) {
        daemonReceiver = new DaemonReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        context.registerReceiver(daemonReceiver, filter);
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void acquire() {
        if (null == wakeLock) {
            PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, LocationUpdateService.class.getCanonicalName());
            if (null != wakeLock) {
                wakeLock.acquire();
            }
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (daemonReceiver != null) {
            unregisterReceiver(daemonReceiver);
        }
        release();
    }

    private void release() {
        if (null != wakeLock) {
            wakeLock.release();
            wakeLock = null;
        }
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        acquire();
        initAMapLocation();
        return START_STICKY;
    }

    /**
     * 停止任务
     */
    public static void stop() {
        OFApplication.getContext().stopService(new Intent(OFApplication.getContext(), LocationUpdateService.class));
    }

    /**
     * 重启任务
     */
    public static void restart() {
        stop();
        OFApplication.getHandler().postDelayed(() -> {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                OFApplication.getContext().startForegroundService(new Intent(OFApplication.getContext(), LocationUpdateService.class));
                OFApplication.getContext().startService(new Intent(OFApplication.getContext(), LocationUpdateService.class));
            }else{
                OFApplication.getContext().startService(new Intent(OFApplication.getContext(), LocationUpdateService.class));
            }
        }, 20);
    }

    /**
     * 初始化高德定位
     */
    private void initAMapLocation(){
        if (mLocationClient != null) {
            return;
        }
        AMapLocationClient.updatePrivacyShow(getApplicationContext(),true,true);
        AMapLocationClient.updatePrivacyAgree(getApplicationContext(),true);
        //初始化定位
        try {
            mLocationClient = new AMapLocationClient(getApplicationContext());
            //设置定位回调监听
            if (mLocationClient == null) {
                return;
            }
            mLocationClient.setLocationListener(mLocationListener);
            //初始化AMapLocationClientOption对象
            mLocationOption = new AMapLocationClientOption();
            AMapLocationClientOption option = new AMapLocationClientOption();
            //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //获取最近3s内精度最高的一次定位结果：
            //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
            mLocationOption.setOnceLocationLatest(true);
            //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
            mLocationOption.setInterval(60*1000);
            //给定位客户端对象设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
            //启动定位
            mLocationClient.startLocation();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }



    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    LogUtils.showLog("定位类型："+aMapLocation.getLocationType() +"纬度 = " + aMapLocation.getLatitude() +"  经度 = "+ aMapLocation.getLongitude());
                    CommonLogical.getInstance().requestUpdateLocation(OFApplication.getContext(), aMapLocation.getLatitude()+"", aMapLocation.getLongitude()+"", null);
                }else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError","location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
        }
    };

    public class DaemonReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            onStartCommand(null, 0, 0);
        }
    }
}
